package cn.factorybox.gateway.filter;

import cn.factorybox.common.utils.IpUtils;
import cn.factorybox.gateway.config.FilterProperties;
import cn.factorybox.gateway.config.JwtProperties;
import cn.factorybox.utils.JwtUtils;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * 获取cookie中的token
 *      通过jwt对token校验
 *      通过：放行；不通过：重定向到登录页
 * @author flypig
 * @version 1.0
 * @date 2019-11-30 19:50
 */
@Component
@EnableConfigurationProperties({JwtProperties.class, FilterProperties.class}) // 启动配置类
public class LoginFilter extends ZuulFilter {

    @Autowired
    private JwtProperties jwtProperties;

    @Autowired
    private FilterProperties filterProperties;

    private static final Logger logger = LoggerFactory.getLogger(LoginFilter.class);

    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 10;
    }

    @Override
    public boolean shouldFilter() {

        // 获取白名单
        List<String> allPaths = this.filterProperties.getAllowPaths();
        // 初始化运行上下文
        RequestContext context = RequestContext.getCurrentContext();
        // 获取request对象
        HttpServletRequest request = context.getRequest();
        // 获取请求的路径
        String url = request.getRequestURI().toString();

        for (String allPath : allPaths) {
           if (StringUtils.contains(url, allPath)) {
               return false;
           }
        }
        return true;
    }

    @Override
    public Object run() throws ZuulException {

        // 初始化运行上下文
        RequestContext ctx = RequestContext.getCurrentContext();
        // 获取request对象
        HttpServletRequest request = ctx.getRequest();

//        String name = request.getHeader("name");
//        System.out.println(name);
        // 获取cookie值
//        String token = CookieUtils.getCookieValue(request, this.jwtProperties.getCookieName());
        String token = request.getHeader("token");
//        System.out.println("token:"+token);

        try {
            JwtUtils.getInfoFromToken(token, this.jwtProperties.getKey());
        } catch (Exception e) {
            // 校验出现异常，返回403
            ctx.setSendZuulResponse(false);
            ctx.setResponseStatusCode(403);
            logger.error("非法访问，未登录，地址：{}", IpUtils.getIpAddr(request), e );
        }
        return null;
    }
}
